package cn.wolfcode.web.controller;

import cn.wolfcode.transfer.domain.Department;
import cn.wolfcode.transfer.domain.Employee;
import cn.wolfcode.transfer.domain.Role;
import cn.wolfcode.transfer.qo.EmployeeQueryObject;
import cn.wolfcode.transfer.qo.JsonResult;
import cn.wolfcode.transfer.qo.PageResult;
import cn.wolfcode.transfer.qo.QueryObject;
import cn.wolfcode.transfer.service.IDepartmentService;
import cn.wolfcode.transfer.service.IEmployeeService;
import cn.wolfcode.transfer.service.impl.EmployeeServiceImpl;
import cn.wolfcode.transfer.util.RequiredPermission;
import cn.wolfcode.transfer.util.UserContext;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private IDepartmentService departmentService;

    @RequestMapping("/list")
    public String list(Model model, EmployeeQueryObject qo) {
        PageInfo<Employee> pageInfo = employeeService.getPageInfo(qo);
        model.addAttribute("qo", qo);
        model.addAttribute("pageInfo", pageInfo);
        List<Department> departments = departmentService.selectAll();
        model.addAttribute("departments", departments);
        return "employee/list";
    }

    @RequiredPermission(name = "员工删除", expression = "employee:delete")
    @RequestMapping("/delete")
    public String delete(Long id) {
        if (id != null) {
            employeeService.deleteByPrimaryKey(id);
        }

        return "redirect:/employee/list";
    }

    @RequiredPermission(name = "员工新增/编辑", expression = "employee:saveOrUpdate")
    @RequestMapping("/input")
    public String update(Long id, Model model) {
        if (id != null) {
            Employee employee = employeeService.selectByPrimaryKey(id);
            model.addAttribute("employee", employee);
            List<Role> employeeRole = employeeService.getEmployeeRole(id);
            model.addAttribute("employeeRole", employeeRole);

        }
        List<Department> departments = departmentService.selectAll();
        model.addAttribute("departments", departments);
        List<Role> roles = employeeService.getRoles();
        model.addAttribute("roles", roles);
        return "employee/input";
    }

    @RequiredPermission(name = "员工新增/编辑", expression = "employee:saveOrUpdate")
    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public JsonResult saveOrUpdate(Employee employee, Long[] ids) {
        if (employee.getId() == null) { // 新增
            if (ids != null) {
                employeeService.insert(employee, ids);
            } else {
                employeeService.insert(employee);
            }
        } else {
            if (ids != null) {
                employeeService.updateByPrimaryKey(employee, ids); // 修改
            } else {
                employeeService.updateByPrimaryKey(employee);
            }
        }
        return new JsonResult(); // 让浏览器重新发一次请求
    }

    @RequiredPermission(name = "密码修改", expression = "employee:UpdatePassword")
    @RequestMapping("/UpdatePassword")
    @ResponseBody
    public JsonResult UpdatePassword(String oldpassword, String newpassword) {

        Employee currentUser = UserContext.getCurrentUser();
        if (!currentUser.getPassword().equals(oldpassword)) {
            throw new RuntimeException("原密码不正确");
        }
            employeeService.UpdatePassword(newpassword, currentUser.getId());
            currentUser.setPassword(newpassword);
            return new JsonResult();
        }

    @RequiredPermission(name = "密码修改", expression = "employee:UpdatePassword")
    @RequestMapping("/inputPassword")
    public String inputPassword() {

        return "/employee/UpdatePassword"; // 让浏览器重新发一次请求
    }

    @RequestMapping("/checkUsername")
    @ResponseBody
    public Map checkUsername(String username) {
        HashMap<String, Boolean> Map = new HashMap<String, Boolean>();
        Employee employee = employeeService.selectByUsername(username);
        Map.put("valid", employee == null);
        return Map;
    }

    @RequiredPermission(name = "员工导出", expression = "employee:exportXls")
    @RequestMapping("/exportXls")
    public void exportXls(HttpServletResponse response) throws Exception {
        //文件下载的响应头（让浏览器访问资源的的时候以下载的方式打开）
//        response.setHeader("Content-Disposition","attachment;filename=employee.xls");
//        //创建excel文件
//        Workbook wb = employeeService.exportXls();
//        //把excel的数据输出给浏览器
//        wb.write(response.getOutputStream());
        Workbook sheets = employeeService.exportXls();
        //创建工作簿

        // 文件下载的响应头
        response.setHeader("Content-Disposition", "attachment;filename=e.xls");
        //把数据传给响应流
        sheets.write(response.getOutputStream());
    }

    @RequiredPermission(name = "员工导入", expression = "employee:importXls")
    @RequestMapping("/importXls")
    public String importXls(MultipartFile file) throws Exception {
        employeeService.importXls(file);
        return "redirect:/employee/list";
    }
    @RequiredPermission(name = "员工禁用/解禁", expression = "employee:updateByStatus")
    @RequestMapping("/updateByStatus")
    public String updateByStatus(boolean status , Long id){
        employeeService.updateByStatus(status,id);
        return "redirect:/employee/list";
    }

    @RequiredPermission(name = "重置密码", expression = "employee:reset")
    @RequestMapping("/reset")
    public String reset(Long id) {
        employeeService.UpdatePassword("1", id);
        Employee currentUser = UserContext.getCurrentUser();
        currentUser.setPassword("1");
        UserContext.setCurrentUser(currentUser);
        return "redirect:/employee/list";
    }

}
